﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Seagull.Configuration;
using Seagull.Events;
using Seagull.IDAL.Stat;
using Seagull.Model.Alerts;
using Seagull.Model.Stat;

namespace Seagull.DAL.Stat
{
    public class StatisticSource : IStatisticSource
    {
        private readonly PathHelper _pathHelper;
        public byte Channel { get; private set; }

        public StatisticSource(byte channel)
        {
            Channel = channel;
            _pathHelper = new PathHelper(Config.Instance.PathConfig.StatFolder, Config.Instance.PathConfig.StatFileExtension);
        }

        public ChannelStatistics GetChannelStatisticsAfter(DateTime startTime)
        {
            try
            {
                using(var statReader = new ChannelStatFileReader(Channel))
                {
                    return statReader.ReadAllAfter(startTime);
                }
            }
            catch(IOException exception)
            {
                AlertEvent.Instance.Publish(new ApplicationAlert(exception, "读取通道统计数据"));
                return new ChannelStatistics();
            }
        }

        public Statistic[] GetFrameStatisticsOfHour(DateTime dateTime)
        {
            var statFile = _pathHelper.GetSegmentFile(new Segment(Channel, dateTime));
            var frameStatFileReader = new FrameStatFileReader(statFile);
            return frameStatFileReader.ReadAll().ToArray();
        }
    }
}
